package cian.controller;

import cian.base.SeeUser;
import cian.dao.UserMapper;
import cian.entity.Pager;
import cian.entity.User;
import cian.service.impl.UserServiceImpl;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

/**
 * Created by Cian on 2017/3/31.
 */
@Controller
public class UserController {

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private UserMapper userMapper;


    private Map<String, User> users = new HashMap<String, User>();

    public UserController() {

        users.put("Cian", new User("Cian", "Ivring", "123","00"));
        users.put("Cian1", new User("Cian1", "Ivring1", "123","00"));
        users.put("Cian2", new User("Cian2", "Ivring2", "123","00"));
    }

    @RequestMapping(value = "/pager",method = RequestMethod.GET)
    public String home(Model model){
        model.addAttribute("totalNum",userService.findAll().size());
        model.addAttribute("pagerUsers",userService.pageHelper("",1,2).getList());
        return "pagerHelp";
    }

    @RequestMapping(value = "/pager/{currentPageNumber}",method = RequestMethod.GET)
    public String test(@PathVariable int currentPageNumber,
                       HttpServletRequest request,
                       Model model){

//        System.out.println(currentPageNumber);
        System.out.println(request.getSession().getAttribute("maxPageItems"));
        int pageSize = 2;
//        System.out.println(currentPageNumber+">>>>>>>>>>>>>>"+pageSize);
        model.addAttribute("totalNum",userService.findAll().size());
        model.addAttribute("pagerUsers",userService.pageHelper("",currentPageNumber,pageSize).getList());
        System.out.println(userService.pageHelper("",currentPageNumber,pageSize).getList().size());
        return "pagerHelp";
    }

    @RequestMapping(value = "/welcome",method = RequestMethod.GET)
    public String welcome(){
        return "welcome";
    }

    @RequestMapping(value = "/users", method = RequestMethod.GET)
    public String listUser(Model model) {
//        model.addAttribute("users", users);
//        model.addAttribute(new User());
        model.addAttribute("users",userService.findAll());
        model.addAttribute(new User());
        return "list";
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(Model model) {
        model.addAttribute(new User());
        return "add";
    }

    @RequestMapping(value = "/update/{username}",method = RequestMethod.GET)
    public String getUpdatePage(Model model,@PathVariable String username){
        User user = userService.findUserByUserName(username);
        model.addAttribute("user",user);
        return "update";
    }

    @RequestMapping(value = "/modify",method = RequestMethod.POST)
    public String modify(User user){
        System.out.println(user.toString());
        userService.modifyByUserName(user);
        return "redirect:/queryAll?pageNow=1&username=";
    }


    @RequestMapping(value = "/{username}", method = RequestMethod.GET)
    public String showUser(Model model,@PathVariable String username) {
        User user = userService.findUserByUserName(username);
        model.addAttribute("user", user);
        return "user";
    }

    @RequestMapping(value = "/{username}/delete",method = RequestMethod.GET)
    public String removeUser(@PathVariable String username){


//        users.remove(username);
        System.out.println(username);
        userService.deleteByName(username);
        return "redirect:/queryAll?pageNow=1&username=";
    }


    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public  String addUser(@Validated User user, BindingResult br, MultipartFile[] attachs, HttpServletRequest req) throws IOException, IOException {

        if(br.hasErrors())
            return "add";
        for (MultipartFile attach :attachs){
            if (attach.isEmpty()) continue;
            System.out.println(attach.getOriginalFilename() + ";" + attach.getContentType()+";"+attach.getName()+"is uploading");
            String realPath=req.getSession().getServletContext().getRealPath("/resources/upload");
            File file =new File(realPath+"/"+attach.getOriginalFilename());
            FileUtils.copyInputStreamToFile(attach.getInputStream(),file);
        }
        System.out.println(user.toString());
        userService.add(user);
        return "addSuccess";
    }


    @RequestMapping(value = "/login" , method = RequestMethod.GET)
    public String loginG(){

        return "login";
    }



    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(User user,
                        HttpSession session,
                        HttpServletResponse response,
                        @CookieValue(value = "username",required = false) String username,
                        @CookieValue(value = "password",required = false) String password){

        if (userService.findUserByUserName(user.getUsername()) != null){    //判断用户存不存在

            String psw = userService.findUserByUserName(user.getUsername()).getPassword();  //获取该用户的正确密码

            if (user.getPassword().equals(psw)){    //判断用户输入密码是否与正确密码匹配

                session.setAttribute("currentUser",user);
//                response.addCookie(cookie);
                return "redirect:/queryAll?pageNow=1&username="; //若用户名和密码匹配，返回hello.jsp页面
            }
        }

        return "loginFailed";   //若用户名和密码不匹配，返回loginFailed.jsp页面
    }

    /*查看操作记录*/
    @RequestMapping("/queryAll")
    public String record(String username,
                         SeeUser seeUser,
                         String pageNow,
                         Model model){
//        System.out.println("------------------"+request.getParameter("username"));
        String user_Name;
        Pager page = null;//new 对象在下面
        user_Name = username;//获取当前登录的用户的loginName
        int totalCount = userMapper.pageHelper(user_Name).size();//获取当前用户总记录条数
//        System.out.println("---------------------tc:"+totalCount);
        if(pageNow != null && pageNow != "") {//防止出现空指针异常
            int pageNow1 = Integer.parseInt(pageNow);
            page = new Pager(pageNow1, totalCount);//这样写的好处，判断完成外面可以继续调用
        }
        seeUser.setUsername(user_Name);
        seeUser.setPage(page);
//        System.out.println("------------------"+page.getStartPos());
//        System.out.println("------------------"+page.getPageSize());
//        System.out.println("-----------------"+page.getStartPos());
//        System.out.println("-----------------"+page.getPageSize());
        List<User> recordList = userMapper.queryAllRecord(seeUser);//取得当前用户的所有操作记录
        model.addAttribute("page",page);
        model.addAttribute("recordList",recordList);
        model.addAttribute("username",user_Name);
//        System.out.println(page.getPageNow());
        return "recordPage";
    }

    @RequestMapping(value = "/aaa",method = RequestMethod.GET)
    public String cian(){
        return "testPager";
    }
}
